package com.tzkyzj.tiremanager.contorller;

import com.tzkyzj.tiremanager.entity.SettlementRecord;
import com.tzkyzj.tiremanager.entity.SettlementItem;
import com.tzkyzj.tiremanager.entity.User;
import com.tzkyzj.tiremanager.service.TireService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Controller
@RequestMapping("/api/settlement")
public class SettlementController {

    private static final Logger logger = LoggerFactory.getLogger(SettlementController.class);

    @Autowired
    private TireService tireService;

    // 获取当前用户
    private User getCurrentUser(HttpServletRequest request) {
        return (User) request.getAttribute("currentUser");
    }

    // 检查用户是否有权限访问运输公司
    private boolean hasAccessToCompany(User user, String company) {
        if (user == null) return false;

        switch (user.getRole()) {
            case ADMIN:
                return true;
            case COMPANY:
                return user.getTransportCompany() != null &&
                        user.getTransportCompany().equals(company);
            case DRIVER:
                return false; // DRIVER角色不能按公司过滤
            default:
                return false;
        }
    }

    /**
     * 保存结算记录
     */
    @PostMapping("/save")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> saveSettlement(@RequestBody Map<String, Object> requestData,
                                                              HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        logger.info("开始保存结算记录, 请求数据: {}", requestData);

        try {
            User currentUser = getCurrentUser(request);

            // 创建结算记录
            SettlementRecord settlementRecord = new SettlementRecord();
            settlementRecord.setPlateNumber((String) requestData.get("plateNumber"));

            // 设置运输公司 - 根据用户角色处理
            String transportCompany = (String) requestData.get("transportCompany");
            if (currentUser.getRole() == User.UserRole.ADMIN) {
                settlementRecord.setTransportCompany(transportCompany);
            } else {
                // 非管理员用户使用自己注册时的公司
                settlementRecord.setTransportCompany(currentUser.getTransportCompany());
            }

            settlementRecord.setRemarks((String) requestData.get("remarks"));
            settlementRecord.setUserId(currentUser.getId()); // 记录创建用户

            // 处理结算日期
            String settlementDateStr = (String) requestData.get("settlementDate");
            if (settlementDateStr != null && !settlementDateStr.isEmpty()) {
                settlementRecord.setSettlementDate(LocalDate.parse(settlementDateStr));
            } else {
                settlementRecord.setSettlementDate(LocalDate.now());
            }

            // 处理费用明细
            List<Map<String, Object>> tireItems = (List<Map<String, Object>>) requestData.get("tireItems");
            if (tireItems != null && !tireItems.isEmpty()) {
                List<SettlementItem> items = tireItems.stream().map(item -> {
                    SettlementItem settlementItem = new SettlementItem();
                    settlementItem.setTireNumber((String) item.get("tireNumber"));
                    settlementItem.setServiceType((String) item.get("serviceType"));

                    // 处理费用字段，确保不为null
                    Object tireCostObj = item.get("tireCost");
                    Object serviceCostObj = item.get("serviceCost");

                    settlementItem.setTireCost(tireCostObj != null ?
                            Double.valueOf(tireCostObj.toString()) : 0.0);
                    settlementItem.setServiceCost(serviceCostObj != null ?
                            Double.valueOf(serviceCostObj.toString()) : 0.0);

                    settlementItem.setRemarks((String) item.get("remarks"));
                    return settlementItem;
                }).collect(Collectors.toList());

                settlementRecord.setItems(items);
            }

            // 保存结算记录
            SettlementRecord savedRecord = tireService.saveSettlementRecord(settlementRecord);

            logger.info("结算记录保存成功, ID: {}, 结算单号: {}, 用户: {}",
                    savedRecord.getId(), savedRecord.getInvoiceNumber(), currentUser.getUsername());

            response.put("success", true);
            response.put("message", "结算记录保存成功");
            response.put("invoiceNumber", savedRecord.getInvoiceNumber());
            response.put("id", savedRecord.getId());
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("保存结算记录失败", e);
            response.put("success", false);
            response.put("message", "保存结算记录失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取结算记录列表（支持角色权限过滤）
     */
    @GetMapping("/records")
    @ResponseBody
    public ResponseEntity<?> getSettlementRecords(
            @RequestParam(required = false) String plateNumber,
            @RequestParam(required = false) String transportCompany,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) Integer limit,
            @RequestParam(required = false) String sort,
            @RequestParam(required = false) String userRole, // 从前端传递的用户角色
            HttpServletRequest request) {

        try {
            User currentUser = getCurrentUser(request);
            logger.info("查询结算记录 - 用户: {}, 角色: {}, 车牌号: {}, 运输公司: {}, 开始日期: {}, 结束日期: {}",
                    currentUser.getUsername(), currentUser.getRole(),
                    plateNumber, transportCompany, startDate, endDate);

            // 权限检查：用户只能查询自己有权限访问的数据
            if (transportCompany != null && !hasAccessToCompany(currentUser, transportCompany)) {
                logger.warn("用户 {} 无权访问运输公司 {} 的数据", currentUser.getUsername(), transportCompany);
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "无权访问该运输公司的数据");
                errorResponse.put("records", List.of());
                return ResponseEntity.status(403).body(errorResponse);
            }

            LocalDate start = null;
            LocalDate end = null;

            // 解析日期参数
            if (startDate != null && !startDate.isEmpty()) {
                try {
                    start = LocalDate.parse(startDate);
                } catch (Exception e) {
                    logger.warn("开始日期格式错误: {}", startDate);
                }
            }

            if (endDate != null && !endDate.isEmpty()) {
                try {
                    end = LocalDate.parse(endDate);
                } catch (Exception e) {
                    logger.warn("结束日期格式错误: {}", endDate);
                }
            }

            List<SettlementRecord> records;

            // 根据用户角色处理查询参数
            String finalTransportCompany = transportCompany;
            String finalPlateNumber = plateNumber;

            // 对于非管理员用户，限制查询范围
            if (currentUser.getRole() != User.UserRole.ADMIN) {
                if (currentUser.getRole() == User.UserRole.COMPANY) {
                    // COMPANY用户只能查看自己公司的记录
                    finalTransportCompany = currentUser.getTransportCompany();
                    logger.info("COMPANY用户限制查询范围: 运输公司={}", finalTransportCompany);
                } else if (currentUser.getRole() == User.UserRole.DRIVER) {
                    // DRIVER用户只能查看自己车辆相关的记录
                    finalPlateNumber = currentUser.getVehiclePlateNumber();
                    logger.info("DRIVER用户限制查询范围: 车牌号={}", finalPlateNumber);
                }
            }

            // 如果没有查询条件，返回最新的记录
            boolean hasSearchCriteria = finalPlateNumber != null || finalTransportCompany != null || start != null || end != null;

            if (!hasSearchCriteria && limit != null && limit > 0) {
                // 返回最新记录（根据用户角色过滤）
                records = tireService.getLatestSettlementRecords(limit, currentUser);
                logger.info("返回用户 {} 的最新 {} 条记录", currentUser.getUsername(), limit);
            } else {
                // 根据条件查询（包含用户角色过滤）
                records = tireService.searchSettlementRecords(finalPlateNumber, finalTransportCompany, start, end, currentUser);
                logger.info("根据条件查询到用户 {} 的 {} 条记录", currentUser.getUsername(), records.size());

                // 如果有限制参数，限制返回数量
                if (limit != null && limit > 0 && records.size() > limit) {
                    records = records.subList(0, limit);
                    logger.info("限制返回 {} 条记录", limit);
                }
            }

            // 记录返回数据的基本信息
            if (!records.isEmpty()) {
                logger.info("返回用户 {} 的记录数量: {}, 第一条记录ID: {}",
                        currentUser.getUsername(), records.size(), records.get(0).getId());
            } else {
                logger.info("用户 {} 未找到匹配的记录", currentUser.getUsername());
            }

            return ResponseEntity.ok(records);

        } catch (Exception e) {
            logger.error("获取结算记录列表失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            errorResponse.put("records", List.of());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 根据ID获取结算记录详情（包含权限检查）
     */
    @GetMapping("/{id}")
    @ResponseBody
    public ResponseEntity<?> getSettlementRecord(@PathVariable Long id, HttpServletRequest request) {
        try {
            User currentUser = getCurrentUser(request);
            logger.info("用户 {} 查询结算记录详情, ID: {}", currentUser.getUsername(), id);

            SettlementRecord record = tireService.getSettlementRecordById(id);
            if (record != null) {
                // 检查权限
                if (!hasAccessToSettlementRecord(currentUser, record)) {
                    logger.warn("用户 {} 无权访问结算记录 {}", currentUser.getUsername(), id);
                    Map<String, Object> errorResponse = new HashMap<>();
                    errorResponse.put("success", false);
                    errorResponse.put("message", "无权访问该结算记录");
                    return ResponseEntity.status(403).body(errorResponse);
                }

                return ResponseEntity.ok(record);
            } else {
                logger.warn("未找到结算记录, ID: {}", id);
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.error("获取结算记录详情失败, ID: {}", id, e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取详情失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 检查用户是否有权限访问结算记录
     */
    private boolean hasAccessToSettlementRecord(User user, SettlementRecord record) {
        if (user == null || record == null) return false;

        switch (user.getRole()) {
            case ADMIN:
                return true;
            case COMPANY:
                return user.getTransportCompany() != null &&
                        user.getTransportCompany().equals(record.getTransportCompany());
            case DRIVER:
                // DRIVER只能查看自己车辆相关的记录
                return user.getVehiclePlateNumber() != null &&
                        user.getVehiclePlateNumber().equals(record.getPlateNumber());
            default:
                return false;
        }
    }

    /**
     * 结算记录车牌号自动补全（支持角色权限过滤）
     */
    @GetMapping("/autocomplete/plate-numbers")
    @ResponseBody
    public ResponseEntity<?> getSettlementPlateNumberSuggestions(@RequestParam String term,
                                                                 HttpServletRequest request) {
        try {
            User currentUser = getCurrentUser(request);
            logger.info("用户 {} 车牌号自动补全查询: {}", currentUser.getUsername(), term);
            List<String> suggestions = tireService.getSettlementPlateNumberSuggestions(term, currentUser);
            return ResponseEntity.ok(suggestions);
        } catch (Exception e) {
            logger.error("车牌号自动补全查询失败", e);
            return ResponseEntity.ok(List.of());
        }
    }

    /**
     * 获取结算统计（支持角色权限过滤）
     */
    @GetMapping("/statistics")
    @ResponseBody
    public ResponseEntity<?> getSettlementStatistics(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String userRole, // 从前端传递的用户角色
            HttpServletRequest request) {

        try {
            User currentUser = getCurrentUser(request);
            logger.info("用户 {} 获取结算统计 - 开始日期: {}, 结束日期: {}",
                    currentUser.getUsername(), startDate, endDate);

            LocalDate start = null;
            LocalDate end = null;

            if (startDate != null && !startDate.isEmpty()) {
                try {
                    start = LocalDate.parse(startDate);
                } catch (Exception e) {
                    logger.warn("开始日期格式错误: {}", startDate);
                }
            }

            if (endDate != null && !endDate.isEmpty()) {
                try {
                    end = LocalDate.parse(endDate);
                } catch (Exception e) {
                    logger.warn("结束日期格式错误: {}", endDate);
                }
            }

            Map<String, Object> statistics = tireService.getSettlementStatistics(start, end, currentUser);
            return ResponseEntity.ok(statistics);

        } catch (Exception e) {
            logger.error("获取结算统计失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取统计失败: " + e.getMessage());
            errorResponse.put("totalRecords", 0);
            errorResponse.put("totalAmount", 0);
            errorResponse.put("serviceTypeStats", Map.of("repair", 0, "install", 0));
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取用户有权限访问的运输公司列表
     */
    @GetMapping("/accessible-companies")
    @ResponseBody
    public ResponseEntity<?> getAccessibleCompanies(HttpServletRequest request) {
        try {
            User currentUser = getCurrentUser(request);
            List<String> companies = tireService.getAccessibleTransportCompanies(currentUser);
            return ResponseEntity.ok(companies);
        } catch (Exception e) {
            logger.error("获取可访问运输公司列表失败", e);
            return ResponseEntity.ok(List.of());
        }
    }

    /**
     * 健康检查端点
     */
    @GetMapping("/health")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "UP");
        response.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(response);
    }
}